package com.sl.crawler.robot.utils;

import com.alibaba.fastjson.JSON;
import com.opencsv.CSVReader;
import com.sl.crawler.common.utils.encode.FileEncoding;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by shiling on 2017/5/26.
 */
public class ConfigUtils {
    private final static Logger LOG = LoggerFactory.getLogger(ConfigUtils.class);

    public static List<String[]> getConfig(String filePath) {
        String fileCharacterEnding = FileEncoding.getFileCharacterEnding(filePath);
        List<String[]> list = new ArrayList<String[]>();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), fileCharacterEnding))) {
            CSVReader csvReader = new CSVReader(br, ',');
            list = csvReader.readAll();
            System.out.println(list);
            LOG.info("配置读入结果为=" + JSON.toJSONString(list));
        } catch (Exception e) {

        }
        return list;
    }


    public static List<List<String>> getConfigList(String filePath) {
        String fileCharacterEnding = FileEncoding.getFileCharacterEnding(filePath);
        List<List<String>> resultList = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), fileCharacterEnding))) {
            CSVReader csvReader = new CSVReader(br, ',');
            List<String[]> list = csvReader.readAll();
            for (String[] array : list) {
                if (array == null || array.length < 3 || StringUtils.isBlank(array[2])) {
                    continue;
                }
                resultList.add(Arrays.asList(array));
            }
            System.out.println(resultList);
            LOG.info("配置读入结果为=" + JSON.toJSONString(resultList));
        } catch (Exception e) {
            LOG.info("配置读入失败=" + filePath);
        }
        return resultList;
    }
}
